package com.cskaoyan.config.realm;

import com.cskaoyan.bean.MarketAdmin;
import com.cskaoyan.bean.MarketAdminExample;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.MarketUserExample;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author : qj
 * @since: 2022/10/13  19:46
 */
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    MarketAdminMapper mapper;

    @Autowired
    MarketUserMapper userMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String type = ((MarketToken) authenticationToken).getType();

        if ("admin".equals(type)){
            MarketAdminExample example = new MarketAdminExample();
            example.createCriteria().andUsernameEqualTo(username);
            List<MarketAdmin> marketAdmins = mapper.selectByExample(example);
            if (marketAdmins.size() == 1){
                MarketAdmin marketAdmin = marketAdmins.get(0);

                return new SimpleAuthenticationInfo(marketAdmin,marketAdmin.getPassword(),getName());
            }
        }else if ("wx".equals(type)){
            MarketUserExample example = new MarketUserExample();
            example.createCriteria().andUsernameEqualTo(username);
            List<MarketUser> marketUsers = userMapper.selectByExample(example);
            if (marketUsers.size() == 1){
                MarketUser marketUser = marketUsers.get(0);

                return new SimpleAuthenticationInfo(marketUser,marketUser.getPassword(),getName());
            }
        }

        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        MarketAdmin primaryPrincipal = (MarketAdmin) principalCollection.getPrimaryPrincipal();
        List<String> permissions = Arrays.asList("aaa");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }


}
